var vehiclesApp = angular.module("vehiclesApp", ["ui.bootstrap","ngRoute"]);
//contextPath: Se obtiene desde el controlador y sirve para determinar la url actual

vehiclesApp
    .factory('vehicles', dataFactory)
    .factory('utils',utilsFactory)
    .factory('gridConfig',gridConfigFactory)
    .service('modalService',modalService)
    .directive('ngJqgrid', ngJqgrid)
    .config(function ($routeProvider, $locationProvider) {
        $locationProvider.hashPrefix('!');
        $routeProvider
            .when('/index',
                {
                    controller: 'indexController',
                    templateUrl: 'index.html'
                })        
            .when('/edit/:id',
                {
                    controller: 'editController',
                    templateUrl: 'edit.html'
                })
            .otherwise({ redirectTo: '/index' });
    });


vehiclesApp.controller("indexController", function($rootScope,$scope, $location, $modal, $log, vehicles, modalService, gridConfig) {
    $scope.init = function(){
        $(window).on('resize', function(event, ui) {
            var parWidth = $("#gbox_grdVehicles01").parent().parent().parent().width();
            var curWidth = $("#gbox_grdVehicles01").width();
            var w = parWidth - 1;
            if (Math.abs(w - curWidth) > 2)
            {  
                $("#grdVehicles01").setGridWidth(w);
            }
        }).trigger('resize');
        
        
    }
    $scope.grid = {};
    
    $scope.refresh = function(){
        $scope.grid.api.refresh();
    }
    
    $scope.goEdit = function(path){
        if($scope.vehicleId)
           $scope.go(path); 
        else{
            var modalOptions = {
                actionButtonText: 'Aceptar',
                bodyText: 'Para poder editar, es necesario seleccionar primero un registro.'
            };
            modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
        }
    }
    
    $scope.go = function ( path ) {
        $location.path( path );
    };
    
    $scope.alerts = [];
    $scope.closeAlert = function(index) {
        $scope.alerts.splice(index, 1);
    };
  
    $scope.delete = function(id){
        if (id) {
            var modalOptions = {
                closeButtonText: 'Cancelar',
                actionButtonText: 'Eliminar',
                bodyText: '¿Estás seguro de eliminar este vehículo?'
            };
            modalService.showModal({}, modalOptions).then(function (result) {
                $scope.loading = true;
                vehicles.delete(contextPath + "delete", {id: id})
                .success(function(data, status, headers, config) {
                    $scope.loading = false;
                    if(data.error){
                        var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: data.error
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                    }else{
                        var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: '¡Registro eliminado con éxito!'
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions).then(function (result){
                             $scope.grid.api.refresh();
                        });
                    }                   
                    })
                .error(function(data, status, headers, config) {
                    $scope.loading = false;
                    var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: 'Ocurrió un error al eliminar el registro.'
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                });
            });
        }else{
            var modalOptions = {
                actionButtonText: 'Aceptar',
                bodyText: 'Para poder eliminar, es necesario seleccionar primero un registro.'
            };
            modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
        }
    }
    
    
    $scope.grid.config = gridConfig.config({
	url: contextPath + "getVehicles",
	colNames: ["id", "Nombre", "Tipo", "type", "status", "Volúmen", "Número Económico", "Capacidad", "Marca", "Placas", "Color", "GPS", "Modelo", "Ancho", "Altura", "Profunidad"],
	colModel: [
		{name: "id", width: 40, align: "right", hidden: true},
		{name: "name", index: "name", width: 120},
		{name: "tipo", index: "tipo", width: 80},
		{name: "type", index: "type", width: 80, hidden: true},
		{name: "status", index: "status", width: 80, hidden: true},
		{name: "volume", index: "volume", width: 50, formatter: 'number', formatoptions: {decimalPlaces: 0, suffix: "ft³"}},
		{name: "economic_number", index: "economic_number", width: 30, hidden: true},
		{name: "capacity", index: "capacity", width: 80},
		{name: "trade_mark", index: "trade_mark", width: 80},
		{name: "plate", index: "plate", width: 80, hidden: true},
		{name: "color", index: "color", width: 80, hidden: true},
		{name: "gps", index: "gps", width: 80, hidden: true},
		{name: "model", index: "model", width: 50},
		{name: "width", index: "width", width: 50},
		{name: "height", index: "height", width: 50},
		{name: "deep", index: "deep", width: 50}
	],
	sortname: "name",
	sortorder: "asc",
	caption: "Vehículos",
        onSelectRow: function(id){
            $scope.$apply(function(){
                $scope.selRow = id;
                $scope.vehicleId = $scope.grid.apicall('getRowData', id).id
            });
            
        },
        loadComplete: function (data) {        
            $scope.$apply(function(){
                $rootScope.data = data; 
                $scope.selRow =null;
                $scope.vehicleId = null;
            });
            $scope.init();
        }
    },{id:"id"});
    
    
    
    $scope.ref = function(){        
	$scope.vehicle =  $scope.grid.apicall('getRowData', $scope.selRow);
    }
   
    
});

vehiclesApp.controller("editController", function($rootScope,$scope, $location, $routeParams, vehicles, utils, modalService) {
    init();
    
    function init() {
        //Catálogos Iniciales
        $scope.vehicleTypes = [{id:0, tipo:'Desconocido'},{id:1,tipo:'Caja Seca'}]
        $scope.vehicleStatus = [{id:0, status:'Inactivo'},{id:1, status:'Activo'}]
        
        //Asignaciones iniciales
        $scope.vehicle = {}
        setSelectedVehicleType(1);
        setSelectedVehicleStatus(1);
        
        var vehicleId = ($routeParams.id) ? parseInt($routeParams.id) : 0;
        if (vehicleId > 0) {
            if($scope.data){
                $scope.vehicle = utils.findById($scope.data[0],'id',vehicleId)
                setSelectedVehicleType($scope.vehicle.type);
                setSelectedVehicleStatus($scope.vehicle.status);
            }else{
                $scope.loading = true;
                vehicles.getData(contextPath + "getVehicles", {page: 1, rowsPerPage: 1, sortField: 'name', sortDir: 'asc', id: vehicleId})
                    .success(function(data, status, headers, config) {
                        $scope.loading = false;
                        $scope.vehicle = data[0][0];
                        setSelectedVehicleType($scope.vehicle.type);
                        setSelectedVehicleStatus($scope.vehicle.status);
                    })
                    .error(function(data, status, headers, config) {
                        alert('Error');
                    });
            }
        }
    }
    
    $scope.save = function(){
        if($scope.vehicle){
            $scope.loading=true;
            vehicles.save(contextPath + "save", $scope.vehicle, {})
                .success(function(data, status, headers, config){
                    $scope.loading=false;
                    if (data.error) {
                         var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: data.error
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                    } else {
                        var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: '¡Registro guardado con éxito!'
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions).then(function (result) {
                                $location.path('/index');
                            });
                        }
                })
                .error(function(data, status, headers, config){
                    $scope.loading = false;
                    alert('Error');
                });
        }
    }
    
    function setSelectedVehicleType(value){
        for(var i=0;i<$scope.vehicleTypes.length;i++){
            if($scope.vehicleTypes[i]["id"]==value){
                $scope.vehicle.type = $scope.vehicleTypes[i]["id"];
                return;
            }
        }
    }
    
    function setSelectedVehicleStatus(value){
        for(var i=0;i<$scope.vehicleStatus.length;i++){
            if($scope.vehicleStatus[i]["id"]==value){
                $scope.vehicle.status = $scope.vehicleStatus[i]["id"];
                return;
            }
        }
    }
    
    $scope.getFormFieldCssClass = function(ngModelController) {
        if(ngModelController.$pristine) return "";
        return ngModelController.$valid ? "has-success" : "has-error";
    }
    
});

